#include "shostakovich.h"
#include <QTimer>
#include <QMouseEvent>
#include <QUrl>
#include <QWindow>

Shostakovich::Shostakovich(QWidget *parent)
    : QWidget(parent), roleLabel(new QLabel(this)), currentFrame(0)
{
    setWindowFlags(Qt::WindowType::FramelessWindowHint);    //无边框
    setAttribute(Qt::WA_TranslucentBackground);             //背景透明

    this->installEventFilter(this);                         //装载函数

    //设置音乐播放
    player = new QMediaPlayer(this);
    player->setMedia(QUrl("D:/QtResources/Shostakovich.mp3"));
    player->setVolume(100);

    //设置图片切换间隔
    QTimer *updateTimer = new QTimer(this);
    updateTimer->callOnTimeout(this, &Shostakovich::updateRoleAnimation);
    updateTimer->start(500);

    //调用函数
    updateRoleAnimation();
    initBtn();

    roleLabel->resize(382,500);     //设置窗口大小
}

Shostakovich::~Shostakovich()
{

}

//循环展示图片
void Shostakovich::updateRoleAnimation()
{
    QString qss("background-repeat:no-repeat;");        //只展示一张图片

    //循环播放图片
    roleLabel->setStyleSheet(qss+QString("background-image:url(://C:/Users/wHy/Pictures/QtResources/Shostakovich/%1.jpg)").arg(currentFrame));
    currentFrame = (currentFrame + 1) % 6 ;
}

//拖动窗口
bool Shostakovich::eventFilter(QObject *watched, QEvent *ev)
{
    QMouseEvent * mouseev = static_cast<QMouseEvent*>(ev);

    static QPoint begpos;       //鼠标点击的坐标

    //当鼠标点击时，记录点击点的坐标
    if(ev->type() == QEvent::MouseButtonPress)
    {
        begpos = mouseev->globalPos() - this->pos();

    }

    //拖动窗口
    else if(ev->type() == QEvent::MouseMove && mouseev->buttons()&Qt::MouseButton::LeftButton)
    {
        this->move(mouseev->globalPos() - begpos);
    }

    //右键图片播放音频
    if(ev->type() == QEvent::MouseButtonPress && mouseev->buttons()&Qt::MouseButton::RightButton)
    {
        if(!isplay) player->play();
        else player->stop();
        isplay = !isplay;
    }

    return false;
}

//按钮设置
void Shostakovich::initBtn()
{
    topBtn = new QPushButton(this);
    closeBtn = new QPushButton(this);

    //按钮位置
    topBtn->setGeometry(331,0,25,25);
    closeBtn->setGeometry(357,0,25,25);

    //设置背景颜色、边框
    topBtn->setStyleSheet("background-image:url(://C:/Users/wHy/Pictures/QtResources/top.png)");
    closeBtn->setStyleSheet("background-image:url(://C:/Users/wHy/Pictures/QtResources/close.png)");
    this->setStyleSheet("QPushButton{background-color:rgb(250,250,250); border:none;}");

    connect(closeBtn, &QPushButton::pressed, this, &Shostakovich::close);        //关闭按钮

    //置顶按钮
    connect(topBtn, &QPushButton::pressed, this, [=]()
    {
        if(!istop)
        {
            QWindow *pWin = this->windowHandle();
            pWin->setFlags(Qt::Widget | Qt::WindowStaysOnTopHint);
        }

        else
        {
            QWindow *pWin = this->windowHandle();
            pWin->setFlags(Qt::Widget);
        }
        istop = !istop;
    });
}

